<?php
function ApplySysUpgrade()
{
	$command_tar = '/bin/tar ';
	$Upgrade_patch = 'Upgrade.patch';
	$Upgrade_tar_gz = 'Upgrade.tar.gz';
	$Upgrade_patch_tar_gz = 'Upgrade_Tmp/patch.tar.gz';
	$Upgrade_exec = 'Upgrade_Tmp/exec.sh';
	$Upgrade_ini = 'Upgrade_Tmp/config.ini';
	$command_chmod = '/bin/chmod ';

	$handle = fopen($Upgrade_patch, "r");
	$contents_string = fread($handle,filesize($Upgrade_patch));
	fclose ($handle);

	#$contents_save = base64_decode($contents_string);
	$contents_save = ($contents_string);

	$handle = fopen($Upgrade_tar_gz, "w+");
	if (fwrite ($handle, $contents_save) == FALSE)
	{
		print "Write file error!";
	}
	fclose($handle);

	$command_string = $command_tar. ' xzf '. $Upgrade_tar_gz;
	shell_exec($command_string);

	$contents_string = '';
	$handle = fopen($Upgrade_patch_tar_gz, 'r');
	$contents_string = fread($handle,filesize($Upgrade_patch_tar_gz));	
	fclose($handle);

	$handle = fopen($Upgrade_exec, 'r');
	$contents_string .= fread($handle,filesize($Upgrade_exec));	
	fclose($handle);
	
	$md5 = md5($contents_string);
	
	$md5_string = '';
	$handle = fopen($Upgrade_ini, 'r');
	$md5_string = fread($handle,filesize($Upgrade_ini));	
	fclose($handle);
	
	/* if ($md5 == $md5_string) */
	{/* Ok, Start Upgrade.*/
		$command_string = $command_chmod. ' +x '. $Upgrade_exec. ' && ./'. $Upgrade_exec. ' > /dev/null';
		shell_exec($command_string);
		return TRUE; /* Success */
	}

	return FALSE; /* False */
}

?>
